/*
 * @Author: FBB
 * @Date: 2020-06-02 14:07:47
 * @LastEditors: FBB
 * @LastEditTime: 2020-06-02 16:34:36
 * @Description: 模仿JQuery实现extend
 *
 * extend的用法：jQuery.extend( target [, object1 ] [, objectN ] )
 */
function extend() {
  const target = arguments[0];
  const options = [...arguments];
  const length = arguments.length;
  for (let i = 1; i < length; i++) {
    const option = options[i];
    if (option) {
      for (const key in option) {
        if (option.hasOwnProperty(key)) {
          target[key] = option[key];
        }
      }
    }
  }
  return target;
}

// JQuery v1.1.4 加入了一个新的用法：jQuery.extend( [deep], target, object1 [, objectN ] )
// deep为可选参数，true表示为深拷贝，false表示浅拷贝，默认为false

function extend1() {
  let deep = false; //默认为false;
  const length = arguments.length;
  let target = arguments[0];
  let i = 1;
  //传入了deep参数的情况
  if (typeof target === "boolean") {
    deep = target;
    target = arguments[1];
    i++;
  }
  if (typeof target !== "object") {
    target = {};
  }
  for (; i < length; i++) {
    let option = arguments[i];
    let clone = null;
    if (option) {
      for (const key in option) {
        let copy = option[key];
        let src = target[key];
        if (deep && copy && typeof copy === "object") {
          if (Array.isArray(copy)) {
            clone = src && Array.isArray(src) ? src : [];
          } else {
            clone = typeof src === "object" ? src : {};
          }
          target[key] = extend1(true, clone, copy);
        } else if (copy) {
          target[key] = copy;
        }
      }
    }
  }
  return target;
}
